package online.longzipeng.back.utils;

import cn.hutool.core.util.StrUtil;
import online.longzipeng.back.common.enums.ResponseEnum;
import online.longzipeng.back.common.exception.MessageException;
import online.longzipeng.back.pojo.entity.User;
import online.longzipeng.back.pojo.vo.UserInfoVo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: lzp
 * @description: 用户工具诶
 * @Date: 2022/6/5
 */
public class UserUtils {

    /**
     * 从请求头中获取当前登录用户的id
     */
    public static Long getUserId() {
        User loginUser = getLoginUser();
        return loginUser.getId();
    }

    /**
     * 获取登录的用户的相关信息
     * // 直接解析token获取
     */
    public static User getLoginUser() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 校验token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            throw new MessageException(ResponseEnum.TOKEN_INVALID);
        }
        return JWTUtils.checkJwtUserInfo(token);
    }

    /**
     * 设置token信息
     *
     * @param userInfo 返回前端的用户信息对象
     * @param user     库中的用户
     */
    public static void setToken(UserInfoVo userInfo, User user) {
        userInfo.setToken(JWTUtils.generateJwtAdmin(user));
    }

}
